package com.dsk.connector.commons.trans;

import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import lombok.Data;

import java.io.Serializable;
import java.sql.Struct;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Data
public class TransMsg implements Serializable {
    private String operation;
    private String tableName;
    private String modifyFields;

    private Map<String,Object> sourcePoint;

    private List<RecordDml> datas;

    public boolean addRecord(RecordDml record){
        if(this.datas==null){
            this.datas=new LinkedList<>();
            this.datas.add(record);
        }else{
            try{
                this.datas.add(record);
            }catch(Throwable e){
                List<RecordDml> list=new LinkedList<>();
                list.addAll(this.datas);
                list.add(record);
                this.datas=list;
            }
        }
        return true;
    }

    public boolean canAdd(RecordDml record){
        if(record==null){
            return false;
        }
        if("alter,drop,create,rename,truncate".contains(this.operation.toLowerCase())){
            return true;
        }
        if(this.operation.equals(record.getOperation()) && this.tableName.equals(record.getTableName()) && this.modifyFields.equals(record.getModifyFields())){
            return true;
        }else{
            return false;
        }
    }

    public String getFirstDDL(){
        if("ddl".equals(this.getOperation())){
            if(this.datas!=null && this.datas.size()>0){
                RecordDdl ddlRecord= (RecordDdl)this.datas.get(0);
                return ddlRecord.getAlterSql();
            }
        }
        return null;
    }

    public String toJsonSourcePoint(){
        if(this.sourcePoint==null){
            return "{}";
        }
        return JSONUtil.parseObj(this.sourcePoint,new JSONConfig().setDateFormat(DatePattern.NORM_DATETIME_PATTERN)).toString();
    }

}
